const dbQuery = require("../db");
const { info } = require("../utils/format");
const formatToHump = require("../utils/formatToHump");

// 搜索群聊
exports.getUserInfos = function (req, res) {
  console.log(req.body.groupName);
  const sql = `select * from group_chat_list where group_name = ?`;
  dbQuery(sql, req.body.groupName, (err, results) => {
    if (err) return res.cc(err);
    res.cc("获取用户成功", 200, formatToHump(results));
  });
};

//创建群聊
exports.createChat = function (req) {
  //console.log(req);
  const sql =
    "insert into group_chat_list(groupId,group_name,group_leader) VALUES(?,?,?)";
  try {
    dbQuery(sql, [req.timestamp, req.content, req.sendId], (err, results) => {
      if (err) console.log(err);
      console.log("写入成功");
    });
  } catch (error) {
    console.log(error);
  }
};

//记录用户加入的群聊
exports.joinGroupChat = function (req) {
  //console.log(req);
  function _AddChat(item) {
    sql = "update user set group_chat_list = ? where id =?";
    dbQuery(sql, [item.list, item.sendId], (err, results) => {
      if (err) console.log(err);
      console.log("写入成功");
    });
  }

  let sql = "select group_chat_list from user where id =? ";
  let list = "";
  try {
    dbQuery(sql, req.sendId, (err, results) => {
      if (err) console.log(err);
      console.log("查询成功");
      if (results && results[0].group_chat_list)
        list = results[0].group_chat_list;
      //list += req.timestamp + ",";
      req.joinGroupId
        ? (list += req.joinGroupId + ",")
        : (list += req.timestamp + ",");
      _AddChat({ list, sendId: req.sendId });
    });
  } catch (error) {
    console.log(error);
  }
};
